import pyautogui
import time
import logging  # 引入logging模块
import os


# 第一步，创建一个logger
class Commonly:
    def __init__(self, logfile):
        self.logger = logging.getLogger()
        self.logger.setLevel(logging.INFO)
        # 第二步，创建一个handler，用于写入日志文件
        self.logfile = logfile
        fh = logging.FileHandler(self.logfile, mode='w')
        fh.setLevel(logging.DEBUG)  # 输出到file的log等级的开关
        # 第三步，定义handler的输出格式
        formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
        fh.setFormatter(formatter)
        self.logger.addHandler(fh)

    def test(self, img, click=False):
        try:
            main_page = pyautogui.locateOnScreen(img, grayscale=True, confidence=0.7)
            print(main_page)
            name = img.split('.')[0]
            self.logger.info("\t打开{0}".format(name))
            x, y = pyautogui.center(main_page)
            if click == True:
                pyautogui.click(x, y)
                self.logger.info("\t{0}功能正常".format(name))
            return (main_page[0], main_page[1])
        except:
            name = img.split('.')[0]
            self.logger.error("\t{0}打开失败或不存在此按钮，需人工检查".format(name))

    def screen(self, app_name, img_name, x, y, w, h):
        im1 = pyautogui.screenshot(region=(x, y, w, h))
        img_path = os.path.dirname(os.getcwd()) + '/Logs/' + app_name + "/运行截图/" + img_name
        im1.save(img_path)
